package com.ricky.chat.client.handler;

import com.ricky.chat.common.dto.JsonMsgDto;
import com.ricky.chat.client.dialog.ChatWindow;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientHandler extends SimpleChannelInboundHandler<JsonMsgDto> {

    private final static Logger LOGGER = LoggerFactory.getLogger(ClientHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, JsonMsgDto msg) {
        ChatWindow.appendMessage(msg.getUserName(),msg.getContent());

        LOGGER.info("======> 收到服务端推送的消息: {}", msg.getContent());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        LOGGER.info("客户端与服务端连接建立成功！");
        // super.channelActive(ctx); // 可以不调用
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("客户端与服务端连接断开！");
        super.channelInactive(ctx); // 可以不调用
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        LOGGER.error("客户端发生异常", cause);
        ctx.close();
    }
}
